import Axios from "axios";
import { Notification, Loading } from "element-ui";

const service = Axios.create({
  baseURL: "https://api.thecatapi.com/v1",
  headers: {
    Accept: "*/*"
  },
  timeout: 5000
});
service.defaults.retry = 4;
service.defaults.retryDelay = 1000;

service.interceptors.request.use(
  config => {
    if (!config.closeLoading) {
      window.loadingInstance = Loading.service();
    }

    config.headers["x-api-key"] = "c5218373-2596-4cf1-aa3b-f65c96fb82ca";

    return config;
  },
  error => {
    Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    if (!response.config.closeLoading) {
      setTimeout(() => {
        window.loadingInstance.close();
      }, 400);
    }

    const res = response;
    if (res.status !== 200) {
      Notification({
        title: "数据返回出错",
        message: "请稍后重试",
        type: "warning"
      });
    } else {
      if (
        response.config.hasOwnProperty("closeInterceptors") &&
        response.config.closeInterceptors
      ) {
        return res.data;
      }
      if (res.status != 200) {
        Notification({
          title: res.statusText,
          type: "warning"
        });
        return Promise.reject("error");
      }
      return res.data;
    }
  },
  error => {
    console.log(error);
    setTimeout(() => {
      window.loadingInstance.close();
    }, 300);
    Notification({
      title: "请求未响应",
      message: "服务器可能出了点问题",
      type: "warning"
    });
    return Promise.reject(error); //千万不能去掉，，，否则请求超时会进入到then方法，导致逻辑错误。
  }
);

export default service;
